<template>
  <div class="question">
    <div v-if="route.path === '/paper/questions'">
      <el-card>
        <!-- 搜索 -->
        <div class="search">
          <el-form :inline="true">
            <el-form-item label="题目ID：">
              <el-input
                v-model="searchForm.id"
                placeholder="请输入题目ID"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="题目内容：">
              <el-input
                v-model="searchForm.title"
                placeholder="请输入题目内容"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="年级：">
              <el-select
                v-model="searchForm.level"
                placeholder="请选择年级"
                clearable
                style="width: 120px"
                @change="handleSearch"
              >
                <el-option
                  v-for="(label, value) in levelMap"
                  :key="value"
                  :label="label"
                  :value="Number(value)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="学科：">
              <el-select
                v-model="searchForm.subjectId"
                placeholder="请选择学科"
                clearable
                :loading="loading"
                style="width: 120px"
                @change="handleSearch"
              >
                <el-option
                  v-for="subject in subjectList"
                  :key="subject.id"
                  :label="`${subject.name} (${subject.levelName})`"
                  :value="subject.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="题型：">
              <el-select
                v-model="searchForm.questionType"
                placeholder="请选择题型"
                clearable
                style="width: 120px"
                @change="handleSearch"
              >
                <el-option
                  v-for="(label, value) in questionTypeMap"
                  :key="value"
                  :label="label"
                  :value="Number(value)"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="loading" @click="handleSearch">查询</el-button>
              <el-button :disabled="loading" style="margin-left: 10px" @click="handleReset">
                重置
              </el-button>
              <el-dropdown style="margin-left: 10px" @command="handleAdd">
                <el-button type="success">
                  添加
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="(label, value) in questionTypeMap"
                      :key="value"
                      :command="Number(value)"
                    >
                      {{ label }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-form-item>
          </el-form>
        </div>

        <!-- 列表 -->
        <el-table :data="questionList" style="width: 100%" :loading="loading" stripe>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="学科" width="150">
            <template #default="{ row }">
              {{ getSubjectName(row.subjectId) }}
            </template>
          </el-table-column>
          <el-table-column label="题型" width="100">
            <template #default="{ row }">
              {{ questionTypeMap[row.questionType] }}
            </template>
          </el-table-column>
          <el-table-column prop="shortTitle" label="题干" width="300" />
          <el-table-column prop="score" label="分数" width="80" />
          <el-table-column prop="difficult" label="难度" width="80" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handlePreview(row)">预览</el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 20px">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 预览对话框 -->
      <el-dialog v-model="previewDialogVisible" title="题目预览" width="800px">
        <el-card>
          <p>
            <strong>学科:</strong>
            {{ getSubjectName(currentQuestion.subjectId) }}
          </p>
          <p>
            <strong>题型:</strong>
            {{ questionTypeMap[currentQuestion.questionType] }}
          </p>
          <p>
            <strong>题干:</strong>
            <span v-html="currentQuestion.title"></span>
          </p>
          <div
            v-if="
              currentQuestion.items &&
              currentQuestion.items.length &&
              currentQuestion.questionType !== 3 &&
              currentQuestion.questionType !== 5
            "
          >
            <p>
              <strong>选项:</strong>
              {{
                currentQuestion.items
                  .map(
                    (item: any, index: number) =>
                      `${String.fromCharCode(65 + index)}. ${stripHtml(item.content)}`
                  )
                  .join(" ")
              }}
            </p>
          </div>
          <p>
            <strong>正确答案:</strong>
            <span v-if="currentQuestion.questionType === 5" v-html="currentQuestion.correct"></span>
            <span v-else-if="currentQuestion.questionType === 4">
              {{
                getFillAnswers(currentQuestion)
                  .map((a: any) => `${a.num}.${a.answer}(${a.score}分)`)
                  .join(" ")
              }}
            </span>
            <span v-else-if="currentQuestion.questionType === 3">
              {{ currentQuestion.correct === "A" ? "是" : "否" }}
            </span>
            <span v-else>{{ currentQuestion.correct }}</span>
          </p>
          <p>
            <strong>解析:</strong>
            <span v-html="currentQuestion.analyze"></span>
          </p>
        </el-card>
      </el-dialog>
    </div>
    <router-view v-else />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import UserAPI from "@/api/system/user.api";
import { ElMessage, ElMessageBox } from "element-plus";

// 去除HTML标签
function stripHtml(html: string) {
  const tmp = document.createElement("DIV");
  tmp.innerHTML = html;
  return tmp.textContent || tmp.innerText || "";
}

// 年级映射
const levelMap: Record<number, string> = {
  1: "一年级",
  2: "二年级",
  3: "三年级",
  4: "四年级",
  5: "五年级",
  6: "六年级",
  7: "初一",
  8: "初二",
  9: "初三",
  10: "高一",
  11: "高二",
  12: "高三",
};

// 题型映射，需要根据实际API定义
const questionTypeMap: Record<number, string> = {
  1: "单选题",
  2: "多选题",
  3: "判断题",
  4: "填空题",
  5: "简答题",
};

const router = useRouter();
const route = useRoute();
const subjectList = ref<any[]>([]);
const questionList = ref<any[]>([]);
const loading = ref(false);
const previewDialogVisible = ref(false);
const currentQuestion = ref<any>({});

const searchForm = reactive({
  id: "",
  title: "",
  level: undefined as number | undefined,
  subjectId: undefined as number | undefined,
  questionType: undefined as number | undefined,
});

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
});

// 获取学科列表
function getSubjectList() {
  UserAPI.getSubjectList()
    .then((data: any) => {
      console.log("学科列表数据:", data);
      subjectList.value = data || [];
    })
    .catch((error) => {
      console.error("获取学科列表失败:", error);
    });
}

function getSubjectName(subjectId: number) {
  const subject = subjectList.value.find((s) => s.id === subjectId);
  return subject ? `${subject.name} (${subject.levelName})` : "未知学科";
}

function getFillAnswers(question: any): { num: number; answer: string; score: string }[] {
  if (!question) return [];
  if (Array.isArray(question.items) && question.items.length > 0) {
    return question.items.map((item: any, index: number) => ({
      num: Number(item.prefix) || index + 1,
      answer: stripHtml(item.content || ""),
      score: item.score ? String(item.score) : "0",
    }));
  }
  try {
    const parsed = JSON.parse(question.correct || "[]");
    if (Array.isArray(parsed)) {
      return parsed.map((item: any, index: number) => ({
        num: item.num ? Number(item.num) : index + 1,
        answer: stripHtml(item.answer || ""),
        score: item.score ? String(item.score) : "0",
      }));
    }
  } catch (error) {
    console.warn("解析填空答案失败:", error);
  }
  return [];
}

// 获取题目列表
function getQuestionList() {
  loading.value = true;
  const payload: any = {
    pageIndex: pagination.current,
    pageSize: pagination.size,
  };
  if (searchForm.id) payload.id = Number(searchForm.id);
  if (searchForm.title) payload.title = searchForm.title;
  if (searchForm.level) payload.level = searchForm.level;
  if (searchForm.subjectId) payload.subjectId = searchForm.subjectId;
  if (searchForm.questionType) payload.questionType = searchForm.questionType;

  UserAPI.getQuestionPage(payload)
    .then((res: any) => {
      questionList.value = res.list || [];
      pagination.total = res.total || 0;
    })
    .catch(() => {
      ElMessage.error("获取题目列表失败");
      questionList.value = [];
      pagination.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleSearch() {
  console.log("搜索参数:", searchForm);
  pagination.current = 1;
  getQuestionList();
}

function handleReset() {
  Object.assign(searchForm, {
    id: "",
    title: "",
    level: undefined,
    subjectId: undefined,
    questionType: undefined,
  });
  pagination.current = 1;
  getQuestionList();
}

function handleAdd(command: number) {
  router.push(`/paper/questions/edit?type=${command}`);
}

function handlePreview(row: any) {
  UserAPI.getQuestionDetail(row.id)
    .then((detail: any) => {
      currentQuestion.value = detail;
      previewDialogVisible.value = true;
    })
    .catch(() => {
      ElMessage.error("获取题目详情失败");
    });
}

function handleEdit(row: any) {
  router.push(`/paper/questions/edit?id=${row.id}`);
}

function handleDelete(row: any) {
  ElMessageBox.confirm("确定删除该题目吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    UserAPI.deleteQuestion(row.id)
      .then(() => {
        ElMessage.success("删除成功");
        getQuestionList();
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
}

function handleSizeChange(size: number) {
  pagination.size = size;
  pagination.current = 1;
  getQuestionList();
}

function handleCurrentChange(current: number) {
  pagination.current = current;
  getQuestionList();
}

onMounted(() => {
  getSubjectList();
  getQuestionList();
});
</script>

<style scoped lang="scss">
.question {
  padding: 16px;
}
</style>
